<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use think\Request;

class Service  extends Controller {

    /*
    登录
    */
    public function login(){
         /**检验用户名和密码是否正确**/
        $username = Request::instance()->post('username').trim();      //接受用户名，并且用trim函数去除首尾空格
        $password = Request::instance()->post('passowrd').trim();       //接受密码，并且用trim函数去除首尾空格
        $return = $this->checkPassword($username,$password);
        if(!$return){
            $res['status'] = 0;
            $res['message'] = "用户名或者密码错误!";
            $this->ajaxReturn($res);
        }else{
            session('admin_id',$return["id"]);             //将admin_id存入session
            session('admin_username',$return["username"]); //将admin_username存入session
            $res['status'] = 1;
            $res['message'] = "登录成功!";
            $this->ajaxReturn($res);
        }
    }
    /*
    验证密码
    */
    public function checkPassword($username,$password){
        $admin = Db::table('roleinfo')->where('tablename',$username)->find();
        // M('admin')->where($map)->find();
        if($admin['password'] === $password){
            return $admin;
        }else{
            return false;
        } 
    }
    /*
	查询操作
    */
    public function select(){
    	$flag = Request::instance()->get('flag');
    	$page=Request::instance()->get('page');
		$limit=Request::instance()->get('limit');
		$now=($page-1)*10;
		$data=Db::table($flag)->limit($now,$limit)->select();
		$count=DB::table($flag)->count();
		return json(0,"success",$count,$data);
    }
    /*
	删除操作
    */
    public function del(){
    	$id = Request::instance()->get('id');
    	$flag = Request::instance()->get('flag');
    	Db::table($flag)->where('id',$id)->delete();
    }
    /*
	修改操作
    */
   public function edit(){
    	$flag = Request::instance()->post('flag');
        $fields = Db::getTableInfo($flag,'fields');
        // print_r($fields);
        foreach ($fields as $key => $value) {
            $data[$value] = Request::instance()->post($value);
        }
        // print_r($data);
        Db::table($flag)->update($data);
    }
    /*
    添加操作
    */
    public function add(){
        $flag = Request::instance()->post('flag');
        $fields = Db::getTableInfo($flag,'fields');
        foreach ($fields as $key => $value) {
            $data[$value] = Request::instance()->post($value);
        }
        Db::table($flag)->insert($data);
    }
}